import os
from flask import Flask,render_template,current_app
from flask_mail import Mail,Message
from threading import Thread
app = Flask(__name__)

#配置邮箱服务器
app.config['MAIL_SERVER'] = os.environ.get('MAIL_SERVER','smtp.qq.com')
#用户名
app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME','2287228249@qq.com')
#密码
app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD','lnmeaytikljfdhje')

mail = Mail(app) #配置文件一定要写在创建Mail对象之前

def async_send_mail(app,msg):
    #发送邮件 需要上下文  但是 新的线程没有上下文 需要手动创建
    with app.app_context():
        mail.send(message=msg)
    pass
def send_mail(to,subject,template,**kwargs):
    #根据current_app 获取当前app的实例
    app = current_app._get_current_object()
    #创建发送对象
    msg = Message(subject=subject,recipients=[to],sender=app.config['MAIL_USERNAME'])
    #浏览器打开看到的内容
    msg.html = render_template(template+'.html',**kwargs)
    #终端 看到的内容
    msg.body = render_template(template + '.txt', **kwargs)
    #创建线程
    thr = Thread(target=async_send_mail,args=[app,msg])
    #启动线程
    thr.start()

    return thr

@app.route('/')
def hello_world():
    #创建发送对象
    send_mail("love_it_so_i_do@foxmail.com","激活用户","activate",username="asdfsdf")
    return '发送成功'


if __name__ == '__main__':
    app.run()
